/*
 * author      :
 * date        : 2019/3/29
 * description : 数据库连接池的一个实现
 * https://blog.csdn.net/frightingforambition/article/details/25464129
 */

package org.wzq.learn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PoolTest {

    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String mysqlUri = "jdbc:mysql://47.106.205.211:3306/high_performance";
        String dbUser = "root";
        String dbPass = "my-secret-ab";

        final Pool pool = new Pool(driver, mysqlUri, dbUser, dbPass);
        try {
            pool.createConnections(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        for (int i = 3; i > 0; i--) {
            new Thread(new Runnable() {
                public void run() {
                    testInThread(pool);
                }
            }).start();
        }
    }

    private static void testInThread(Pool pool) {
        Connection conn = pool.getConnection();
        String threadId = "Thread " + Thread.currentThread().getId();
        System.out.println(threadId + " got conn");
        try {
            String sql = "select * from user1";
            PreparedStatement ps;
            ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                User1 user1 = new User1();
                user1.setId(rs.getInt("id"));
                user1.setName(rs.getString("name"));
                user1.setSex(rs.getString("sex"));
                System.out.println(threadId + ": " + user1);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println(threadId + ": return conn");

            pool.returnConnection(conn);
        }
    }
}